﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.AspNet.SignalR;
using Popw.LiveBlog.Hubs;
using Popw.LiveBlog.Models;
using Popw.LiveBlog.Repositories;

namespace Popw.LiveBlog.Services
{
	public interface IContentService
	{
		List<ContentItem> GetTop();
		ContentItem Item(int contentItemID);
		List<ContentItem> GetGetTopContentItemsAfterTimeTop(DateTime lastTime);
		void SaveContentItem(ContentItem contentItem);
		int GetOldestID();
		void Delete(int contentItemID);
		string ParseUrlsAndYouTube(string text);
	}

	public class ContentService : IContentService
	{
		private readonly IContentItemRepo _contentItemRepo;

		public ContentService(IContentItemRepo contentItemRepo)
		{
			_contentItemRepo = contentItemRepo;
		}

		public const string PartitionKey = "Event";
		public const int TakeCount = 10;

		public List<ContentItem> GetTop()
		{
			return _contentItemRepo.GetTopContentItems(TakeCount);
		}

		public ContentItem Item(int contentItemID)
		{
			return _contentItemRepo.Get(contentItemID);
		}

		public List<ContentItem> GetGetTopContentItemsAfterTimeTop(DateTime lastTime)
		{
			return _contentItemRepo.GetTopContentItemsAfterTime(TakeCount, lastTime);
		}

		public void SaveContentItem(ContentItem contentItem)
		{
			contentItem.PostTime = DateTime.UtcNow;
			_contentItemRepo.SaveContentItem(contentItem);
			var context = GlobalHost.ConnectionManager.GetHubContext<MainHub>();
			context.Clients.All.notifyFeed(contentItem);
		}

		public int GetOldestID()
		{
			return _contentItemRepo.GetOldestID();
		}

		public void Delete(int contentItemID)
		{
			_contentItemRepo.Delete(contentItemID);
		}

		public string ParseUrlsAndYouTube(string text)
		{
			var matches = ProtocolPattern.Matches(text);
			foreach (Match item in matches)
			{
				var uri = new Uri(item.Value);
				if (uri.Host.Contains("youtube"))
				{
					var q = uri.Query.Remove(0, 1).Split('&').Where(x => x.Contains("=")).Select(x => new KeyValuePair<string, string>(x.Split('=')[0], x.Split('=')[1]));
					var dictionary = q.ToDictionary(pair => pair.Key, pair => pair.Value);
					if (dictionary.Any(x => x.Key == "v"))
					{
						text = text.Replace(item.Value, String.Format(@"<iframe width=""853"" height=""480"" src=""http://www.youtube.com/embed/{0}"" frameborder=""0"" allowfullscreen></iframe>", dictionary["v"]));
					}
				}
				else if (uri.Host.Contains("youtu.be"))
				{
					var v = uri.Segments[1];
					text = text.Replace(item.Value, String.Format(@"<iframe width=""853"" height=""480"" src=""http://www.youtube.com/embed/{0}"" frameborder=""0"" allowfullscreen></iframe>", v));
				}
				else
				{
					text = text.Replace(item.Value, String.Format("<a href=\"{0}\" target=\"_blank\">{0}</a>", item.Value));
				}
			}
			return text;
		}

		private readonly static Regex ProtocolPattern = new Regex(@"(?<![\]""\>=])(((news|(ht|f)tp(s?))\://)[\w\-\*]+(\.[\w\-/~\*]+)*/?)([\w\?=&/;\+%\*\:~,\.\-\$\|@#])*", RegexOptions.Compiled | RegexOptions.IgnoreCase);
	}
}